package com.xuyiwei.xblog.core.base.warpper;

import com.xuyiwei.xblog.core.exception.GunsException;
import com.xuyiwei.xblog.core.util.ObjectUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 控制器查询结果的包装类基类
 *
 * @author fengshuonan
 * @date 2017年2月13日 下午10:49:36
 */
public abstract class BaseControllerWarpper {

    public Object obj = null;

    public BaseControllerWarpper(Object obj) {
        this.obj = obj;
    }

    @SuppressWarnings("unchecked")
    public Object warp() {
        if (this.obj instanceof List) {
            List<Map<String, Object>> result = new ArrayList<>();
            List<Object> list = (List<Object>) this.obj;
            for(Object ob:list){
                if(ob instanceof Map){
                    Map<String, Object> map = (Map<String, Object>) ob;
                    warpTheMap(map);
                    result.add(map);
                }else{
                    Map<String, Object> map = null;
                    try {
                        map = ObjectUtil.objectToMap(ob);
                    } catch (IllegalAccessException e) {
                         throw new GunsException("500","数据转换错误");
                    }
                    warpTheMap(map);
                    result.add(map);
                }
            }
            return result;
        } else if (this.obj instanceof Map) {
            Map<String, Object> map = (Map<String, Object>) this.obj;
            warpTheMap(map);
            return map;
        } else {
            Map<String, Object> map = null;
            try {
                map = ObjectUtil.objectToMap(this.obj);
            } catch (IllegalAccessException e) {
                throw new GunsException("500","数据转换错误");
            }
            warpTheMap(map);
            return map;
        }
    }

    protected abstract void warpTheMap(Map<String, Object> map);
}
